package com.tuling.code.ratelimit;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
 * 基础版本，不能解决突然间并发量增加，需要增加时间窗口算法
 * 改版见：Guava实现例子 --> RateLimitTester
 * @author lenovo
 *
 */
public class CountTest {
	static int limit = 10;
	static int request = 0;
	static int interval = 60;//时钟周期
	static long start = System.currentTimeMillis();
	
	public static void main(String[] args) {
		ExecutorService excService = Executors.newFixedThreadPool(10);
		for (int i = 0; i < 100; i++) {
			excService.submit(()-> handle());
		}
	}
	
	private static void handle() {
		boolean acquire = acquire();
		try {
			if(acquire){
				Thread.sleep(2000);
				System.out.println("========业务执行中=======");
			}else {
				System.out.println("**************我被拒绝了**************");
			}
		} catch(Exception e){
			e.printStackTrace();
		}
	}
	
	private static boolean acquire(){
		long now = System.currentTimeMillis();
		//判断是否是当前周期的
		if(now > start + interval){
			//已经是新的周期的
			start = now; //开启新周期新纪元
			request = 0;
			return true;
		} 
		request ++;
		return request < limit;
	}
}
